package com.chuji.crmcj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.CarTypeStockActivity;
import com.chuji.crmcj.act.InsureCalAct;
import com.chuji.crmcj.act.LendCounterActivity;
import com.chuji.crmcj.act.MainActivity;
import com.chuji.crmcj.act.NewtaskActivity;
import com.chuji.crmcj.act.NoticeActivity;
import com.chuji.crmcj.act.OrderListAct;
import com.chuji.crmcj.act.PotentialListAct;
import com.chuji.crmcj.act.ReceptionActivity;
import com.chuji.crmcj.act.SearchActivity;
import com.chuji.crmcj.act.SellLoseApproveActivity;
import com.chuji.crmcj.act.TenureListAct;
import com.chuji.crmcj.act.TodayTaskActivity;
import com.chuji.crmcj.act.WorkFormActivity;
import com.chuji.crmcj.adapter.ToolsAdapter;
import com.chuji.crmcj.bean.GetNumInfo;
import com.chuji.crmcj.bean.NewReceInfo;
import com.chuji.crmcj.bean.PerformanceInfo;
import com.chuji.crmcj.utils.CommonUtil;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;

/**
 * Created by w.pitt on 2016/1/28.
 */
public class SaleHomeFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView mTvReceptionIcon;
    private ImageView mTvDayIcon;
    private TextView mTvWeek;
    private TextView mTvDate;
    private GridView mGvWorkExpand;
    private RelativeLayout mRlNewTask;
    private RelativeLayout mRlPotential;
    private RelativeLayout mRlOrder;
    private View mRltenure;
    private RelativeLayout mRlToDayTask;
    private PerformanceInfo performanceInfo;
    private View view;
    private TextView mTotalAmount;
    private TextView mTvSort;
    private String userID;
    private NewReceInfo newReceInfo;
    private View viewLine;
    private GetNumInfo hiddenNumInfo;
    private TextView mTvHiddenNum;
    private TextView mTvOrderNum;
    private TextView mTvRetainNum;
    private RelativeLayout mRlSearch;
    private ScrollView mScrollview;
    private TextView mTvTime;
    private AutoTask task;
    private ToolsAdapter adapter;
    private Toast toast;
    private int free;
    private String flowID;
    private int num;


    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = View.inflate(UIUtils.getContext(), R.layout.page_sale_home, null);

        fl_loading = (FrameLayout) view.findViewById(R.id.fl_loading);
        mRlNewTask = (RelativeLayout) view.findViewById(R.id.rl_new_task);
        mTvReceptionIcon = (ImageView) view.findViewById(R.id.tv_reception_icon);
        mTvDayIcon = (ImageView) view.findViewById(R.id.tv_day_icon);
        mTvWeek = (TextView) view.findViewById(R.id.tv_week);
        mTvTime = (TextView) view.findViewById(R.id.tv_time);
        mTvDate = (TextView) view.findViewById(R.id.tv_date);
        mRlSearch = (RelativeLayout) view.findViewById(R.id.rl_searchBar);
        mGvWorkExpand = (GridView) view.findViewById(R.id.gv_work_expand);
        mRlPotential = (RelativeLayout) view.findViewById(R.id.rl_potential);
        mRlOrder = (RelativeLayout) view.findViewById(R.id.rl_order);
        mRltenure = view.findViewById(R.id.rl_tenure);
        mRlToDayTask = (RelativeLayout) view.findViewById(R.id.rl_today_task);
        mTotalAmount = (TextView) view.findViewById(R.id.tv_totalamount);
        mTvSort = (TextView) view.findViewById(R.id.tv_sort);
        viewLine = view.findViewById(R.id.viewline);
        mTvHiddenNum = (TextView) view.findViewById(R.id.tv_potential_number);
        mTvOrderNum = (TextView) view.findViewById(R.id.tv_order_number);
        mTvRetainNum = (TextView) view.findViewById(R.id.tv_tenure_number);
        mScrollview = (ScrollView) view.findViewById(R.id.sl_home_page);
        mScrollview.smoothScrollTo(0, 20);
        mGvWorkExpand.setFocusable(false);

        initData();
        return view;
    }

    private boolean isFirst = true;

    @Override
    public void onStart() {
        super.onStart();

        //请求未读消息
        reqNotReNotic();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 点击完 有效 或者无效后才会消失。
//        int isShow = SPUtils.getInt(UIUtils.getContext(), "IsShow", -1);
//        if (isShow == 1) {
//            // 恒等于1消失
//            viewLine.setVisibility(View.GONE);
//            mRlNewTask.setVisibility(View.GONE);
//        }
        flowID = SPUtils.getString(UIUtils.getContext(), "FlowID", "");
        free = SPUtils.getInt(UIUtils.getContext(), "Free", 1);

        task = new AutoTask();
        if (!flowID.equals("")) {
            viewLine.setVisibility(View.VISIBLE);
            mRlNewTask.setVisibility(View.VISIBLE);
        } else if (free == 1) {
            viewLine.setVisibility(View.GONE);
            mRlNewTask.setVisibility(View.GONE);
            //空闲状态
            task.start();
        } else {
            task.stop();
        }
//        new Thread(new ThreadShow()).start();
    }

    //    // handler类接收数据
//    Handler handler = new Handler() {
//        public void handleMessage(Message msg) {
//            if (msg.what == 1) {
//                System.out.println("receive....");
//                //请求是否有新的接待
//                reqNewReception();
//            }
//        }
//    };
//
//    // 线程类
//    class ThreadShow implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    if (handler != null) {
//                        Thread.sleep(5000);
//                        Message msg = new Message();
//                        msg.what = 1;
//                        handler.sendMessage(msg);
//                        System.out.println("send...");
//                    }
//                } catch (Exception e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                    System.out.println("thread error...");
//                }
//            }
//        }
//    }

    private class AutoTask implements Runnable {
        private boolean flag = false;

        @Override
        public void run() {
            if (flag) {
                UIUtils.postDelayed(this, 5000);
                //请求是否有新的接待
                reqNewReception();
            }
        }

        public void start() {
            if (!flag) {
                flag = true;
                UIUtils.removeCallbacks(this);
                if (isFirst) {
                    UIUtils.postDelayed(this, 0);
                    isFirst = false;
                } else {
                    UIUtils.postDelayed(this, 5000);
                }
            }
        }

        public void stop() {
            if (flag) {
                UIUtils.removeCallbacks(this);
                flag = false;
            }
        }
    }

    @Override
    public void initData() {
        mTvDate.setText(CommonUtil.getStringDate("MM/dd EEEE"));
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");

        //网络请求
        requestNetData();
//        ToolsAdapter adapter = new ToolsAdapter(0, 3);
//        mGvWorkExpand.setAdapter(adapter);
    }

    private void requestNetData() {
        //请求销售额和排名
        reqPerformance();
        //请求潜客数量
        reqHiddenCount();
        //请求订单客户数量
        reqOrdPasCount();
        //请求保有客户
        reqRetainCount();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onPause() {
        super.onPause();
        task.stop();
    }

    private void reqNotReNotic() {
        String strURL = String.format(UrlUtils.GETMYMESSAGECOUNT + "&SalesID=%s&CarModel=&PageSize=10&PageIndex=1", userID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final GetNumInfo notReNotice = JSON.parseObject(s, GetNumInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (notReNotice.getApiParamObj().size() != 0) {
//                            if (adapter == null) {
//                                num = notReNotice.getApiParamObj().get(0).getNum();
                            adapter = new ToolsAdapter(0, num);
                            mGvWorkExpand.setAdapter(adapter);
//                            } else {
//                                num = adapter.getNotices();
//                                num = notReNotice.getApiParamObj().get(0).getNum();
//                                adapter.notifyDataSetChanged();
//                            }
                            fl_loading.setVisibility(View.GONE);
                        }
                    }
                });
            }
        });
    }

    private void reqRetainCount() {
        String strURL = UrlUtils.GETRETAINCOUNT + "&SalesID=" + userID;
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final GetNumInfo retainInfo = JSON.parseObject(s, GetNumInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (retainInfo.getApiParamObj().size() != 0) {
                            mTvRetainNum.setText(String.valueOf(retainInfo.getApiParamObj().get(0).getNum()));
                        }
                    }
                });
            }
        });
    }

    private void reqOrdPasCount() {
        String strURL = UrlUtils.GETORDPASCOUNT + "&SalesID=" + userID;
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final GetNumInfo orderInfo = JSON.parseObject(s, GetNumInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (orderInfo.getApiParamObj().size() != 0) {
                            mTvOrderNum.setText(String.valueOf(orderInfo.getApiParamObj().get(0).getNum()));
                        }
                    }
                });
            }
        });
    }

    private void reqHiddenCount() {
        String strURL = UrlUtils.GETHIDDENCOUNT + "&SalesID=" + userID;
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                hiddenNumInfo = JSON.parseObject(s, GetNumInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (hiddenNumInfo.getApiParamObj().size() != 0) {
                            mTvHiddenNum.setText(String.valueOf(hiddenNumInfo.getApiParamObj().get(0).getNum()));
                        }
                    }
                });
            }
        });
    }

    private void reqNewReception() {
        String strURL = UrlUtils.ISHAVERECEPTION + "&SalesID=" + userID;
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                newReceInfo = JSON.parseObject(s, NewReceInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (newReceInfo.getApiParamObj().get(0).getState() == 1) {
                            UIUtils.showToastSafe("请注意，您有新的接待");
                            mRlNewTask.setVisibility(View.VISIBLE);
                            viewLine.setVisibility(View.VISIBLE);
                            mTvTime.setText(newReceInfo.getApiParamObj().get(0).getEnterTime());
                            task.stop();
                        } else {
//                            UIUtils.showToastSafe("无新的接待");
                        }
                    }
                });
            }
        });
    }

    private void reqPerformance() {
        String strURL = UrlUtils.GETPERFORMANCE + "&SalesID=" + userID;
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                performanceInfo = JSON.parseObject(s, PerformanceInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (performanceInfo.getCount() == 0) {
                            UIUtils.showToastSafe("无销售排名");
                        } else {
                            mTotalAmount.setText(performanceInfo.getApiParamObj().get(0).getTotalAmount());
                            mTvSort.setText(performanceInfo.getApiParamObj().get(0).getXh());
                        }
                    }
                });
            }
        });
    }

    @Override
    public void initListener() {
        mRlNewTask.setOnClickListener(this);
        mRlPotential.setOnClickListener(this);
        mRlOrder.setOnClickListener(this);
        mRltenure.setOnClickListener(this);
        mGvWorkExpand.setOnItemClickListener(this);
        mRlToDayTask.setOnClickListener(this);
        mRlSearch.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_new_task:
                if (!flowID.equals("")) {
                    mContext.startActivity(new Intent(mContext, ReceptionActivity.class));
                } else {
                    mContext.startActivity(new Intent(mContext, NewtaskActivity.class));
                }
//                ((MainActivity) mContext).overridePendingTransition(R.anim.act_in, 0);
                // 设置动画
                ((MainActivity) mContext).overridePendingTransition(R.anim.act_in, 0);
                break;
            case R.id.rl_potential:
                ((MainActivity) mContext).startActivity(new Intent(mContext, PotentialListAct.class));
                break;
            case R.id.rl_order:
                ((MainActivity) mContext).startActivity(new Intent(mContext, OrderListAct.class));
                break;
            case R.id.rl_tenure:
                ((MainActivity) mContext).startActivity(new Intent(mContext, TenureListAct.class));
                break;
            case R.id.rl_today_task:
                UIUtils.startActivity(new Intent(mContext, TodayTaskActivity.class));
                break;
            case R.id.rl_searchBar:
                UIUtils.startActivity(new Intent(mContext, SearchActivity.class));
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (position) {
            case 0:
                UIUtils.startActivity(new Intent(mContext, CarTypeStockActivity.class));
                break;
            case 1:
                UIUtils.startActivity(new Intent(mContext, NoticeActivity.class));
                break;
            case 2:
                UIUtils.startActivity(new Intent(mContext, SellLoseApproveActivity.class));
                break;
            case 3:
                UIUtils.startActivity(new Intent(mContext, LendCounterActivity.class));
                break;
            case 4:
                UIUtils.startActivity(new Intent(mContext, InsureCalAct.class));
                break;
            case 5:
                UIUtils.startActivity(new Intent(mContext, WorkFormActivity.class));
                break;
        }
    }

//    @Override
    //为了防止万一程序被销毁的风险，这个方法可以保证重要数据的正确性
    //不写这个方法并不意味着一定出错，但是一旦遇到了一些非常奇怪的数据问题的时候
    //可以看看是不是由于某些重要的数据没有保存，在程序被销毁时被重置
//    public void onSaveInstanceState(Bundle savedInstanceState) {
//        // Save away the original text, so we still have it if the activity
//        // needs to be killed while paused.
//        savedInstanceState.putBoolean("isFirst", isFirst);
//        super.onSaveInstanceState(savedInstanceState);
//    }
//
//    @Override
//    public void onViewStateRestored(Bundle savedInstanceState) {
//        super.onViewStateRestored(savedInstanceState);
//        if (savedInstanceState != null) {
//            isFirst = savedInstanceState.getBoolean("isFirst");
//            System.out.println(isFirst + "--------------------isFirst");
//            UIUtils.showToastSafe(isFirst + "1111111111111111111111111111111111111111111");
//        }
//    }
}
